<template>
  <div class="app-container">
    <el-form :model="searchForm" label-width="100px" @keyup.enter.native="search()">
      <el-row>
        <el-col class="other">
          <el-form-item label="标题" size="small">
            <el-input v-model="searchForm.title"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="professions">
          <el-form-item label="类型" size="small">
            <el-select v-model="searchForm.type" placeholder="请选择">
              <el-option value="" label="全部"></el-option>
              <el-option
                v-for="item in typeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col class="other">
          <el-form-item label="读取状态：" size="small">
            <el-select v-model="searchForm.readFlag" placeholder="请选择">
              <el-option value="" label="全部"></el-option>
              <el-option
                v-for="item in readFlagList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col class="other">
          <el-form-item label="状态：" size="small">
            <el-radio-group v-model="searchForm.status">
              <el-radio label=2>草稿</el-radio>
              <el-radio label=1>发布</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="3">
          <el-form-item size="small">
            <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="table-btn">
      <el-button type="primary" size="small" icon="el-icon-plus" @click="addTeam()">添加</el-button>
      <div style="font-size: 12px;display: inline-block">
        <div class="green nomal"></div>
        <span>已读</span>
        <div class="red nomal"></div>
        <span>未读</span>
      </div>
      <el-dialog :title="dialogTitle" :visible.sync="outerVisible" width="600px" @close="getUnreadCount()">
        <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="100px">
          <el-form-item prop="type" label="类型" size="small" class="input">
            <el-select v-model="teamRow.type" placeholder="请选择">
              <el-option
                v-for="item in typeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="status" label="状态：" size="small">
            <el-radio-group v-model="teamRow.status">
              <el-radio label=2>草稿</el-radio>
              <el-radio label=1>发布</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="title" label="标题" size="small" class="input">
            <el-input v-model="teamRow.title"></el-input>
          </el-form-item>
          <el-form-item label="附件" size="small">
            <input id="file" type="file" ref='file' @change="getFile($event)">
          </el-form-item>
          <el-form-item label="内容" size="small" class="textarea">
            <el-input type="textarea" :autosize="{ minRows: 8, maxRows: 10}" v-model="teamRow.content"></el-input>
          </el-form-item>
          <el-form-item label="接收人类型" size="small" prop="roleType">
            <el-checkbox-group v-model="teamRow.roleType" @change="judge()">
              <el-checkbox v-for="item in global.positionList" :label="item.value" :key="item.value">
                {{item.label}}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="warning" size="small"  @click="submitForm('teamRow')" v-no-more-click>确定</el-button>
          <el-button size="small" @click="outerVisible = false">取消</el-button>
        </div>
      </el-dialog>
      <el-dialog :title="dialogTitle1" :visible.sync="outerVisible1" width="810px" @close="closeDialog()">
        <el-form ref="teamRow1" :model="teamRow1" label-width="100px">
          <el-form-item prop="type" label="类型" size="small" class="input">
            <el-select v-model="teamRow1.type" placeholder="请选择">
              <el-option
                v-for="item in typeList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="status" label="状态：" size="small">
            <el-radio-group v-model="teamRow1.status">
              <el-radio label=2>草稿</el-radio>
              <el-radio label=1>发布</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="title" label="标题" size="small" class="input">
            <el-input v-model="teamRow1.title"></el-input>
          </el-form-item>
          <el-form-item label="内容" size="small" class="textarea">
            <el-input type="textarea" :autosize="{ minRows: 8, maxRows: 10}" v-model="teamRow1.content"></el-input>
          </el-form-item>
        </el-form>
        <my-table
          class="pagination"
          :data="tableData1"
          :col-configs="colConfigs1"
          v-loading="listLoading1"
          :page-num="pageNum1"
          :page-size="pageSize1"
        >

        </my-table>
        <el-pagination
          v-if="!listLoading1"
          class="pagination"
          @size-change="handleSizeChange1"
          @current-change="handleCurrentChange1"
          :current-page="pageNum1"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize1"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total1">
        </el-pagination>
        <div class="span" v-if="!listLoading1">
          <span>已查阅：{{this.read}}</span>
          <span>未查阅：{{this.notRead}}</span>
          <span>总共：{{this.sum}}</span>
        </div>
      </el-dialog>
      <!--<el-button size="small" icon="el-icon-upload2">导出</el-button>-->
    </div>
    <my-table
      :data="tableData"
      :col-configs="colConfigs"
      :page-num="pageNum"
      :page-size="pageSize"
      v-loading="listLoading">
      <el-table-column
        slot="opt"
        fixed="left"
        label="阅读状态"
        width="80">
        <template slot-scope="scope">
          <img class="img" v-if="scope.row.readFlag ===  '1'" src="../../../assets/infor_images/read.png">
          <img class="img" v-else src="../../../assets/infor_images/notread.png">
        </template>
      </el-table-column>
      <el-table-column
        slot="opt"
        fixed="right"
        label="操作"
        width="250">
        <template slot-scope="scope">
          <el-popover
            v-if="scope.row.isAllow === 0 && scope.row.type === '4'"
            placement="top"
            width="160"
            :ref="`popover-allowView${scope.$index}`"
          >
            <p>确定允许查看吗?</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-allowView${scope.$index}`].doClose()">取消
              </el-button>
              <el-button type="primary" size="mini" @click.native.prevent="allowView(scope)">确定</el-button>
            </div>
            <el-button type="text" size="small" slot="reference" v-popover:popover-allowView${scope.$index}>允许查看
            </el-button>
          </el-popover>
          <el-button
            v-if="scope.row.status == 1"
            @click.native.prevent="lookTeam(scope.row)"
            type="text"
            size="small">
            查看
          </el-button>
          <a v-if="scope.row.files" target="_blank" :href="global.filePathUrl+encodeURI(scope.row.files)">下载</a>
          <el-button
            v-if="(scope.row.userId == userId || roleType == 0 || roleType == 1 )&& scope.row.type!=='3'"
            @click.native.prevent="editTeam(scope.row.notifyId)"
            type="text"
            size="small">
            修改
          </el-button>
          <el-button
            v-if="scope.row.readFlag !== '1'"
            @click.native.prevent="notWarn(scope.row.notifyId)"
            type="text"
            size="small">
            不再提醒
          </el-button>
          <el-popover
            v-if="(scope.row.userId == userId || roleType == 0 || roleType == 1 )&& scope.row.type!=='3'"
            placement="top"
            width="160"
            :ref="`popover-${scope.$index}`"
          >
            <p>确定删除这条数据吗?</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-${scope.$index}`].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click.native.prevent="deleteRow(scope)">确定</el-button>
            </div>
            <el-button type="text" size="small" slot="reference" v-popover:popover-${scope.$index}>删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>

<script>
  import {
    addSysteminfor,
    deleteSysteminfor,
    getList,
    lookChart,
    updateSysteminfor,
    selectSysteminfor,
    getUnreadCount,
    notWarn,
    isAllow
  } from '@/api/systeminfor'
  import myTable from '@/components/myTable'
  import global from '@/components/global'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate } from '@/utils/index'

  const type = function(row, column) {
    if (parseInt(row.type) === 1) {
      return '会议通告'
    } else if (parseInt(row.type) === 2) {
      return '业务处理'
    } else if ((parseInt(row.type) === 3)) {
      return '未到账'
    } else if ((parseInt(row.type) === 4)) {
      return '请求查看'
    } else {
      return '证件过期类型'
    }
  }

  const roleType = function(row, column) {
    let obj = {}
    const arr = row.roleType ? row.roleType.split(',') : ''
    const newarr = []
    for (let i = 0; i < arr.length; i++) {
      obj = global.positionList.find((item) => {
        return item.value === parseInt(arr[i]) // 筛选出匹配数据
      })
      newarr[i] = obj.label
    }
    return newarr.join(',')
  }

  const status = function(row, column) {
    if (parseInt(row.status) === 1) {
      return '发布'
    } else {
      return '草稿'
    }
  }
  const readFlag = function(row, column) {
    if (row.readFlag === '1') {
      return '已读'
    } else {
      return '未读'
    }
  }

  const time = {
    props: ['colConfig'],
    filters: {
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatDate }}
      </span>
  </el-table-column>
  `
  }

  export default {
    components: {
      myTable,
      AreaSelect
    },
    data() {
      return {
        colConfigs: [
          { prop: 'title', label: '标题', width: '200' },
          { prop: 'type', label: '类型', width: '150', formatter: type },
          { prop: 'status', label: '状态', width: '150', formatter: status },
          { prop: 'createBy', label: '创建者', width: '150' },
          { prop: 'roleType', label: '接收人类型', width: '150', formatter: roleType },
          { prop: 'createDate', label: '创建时间', width: '150', component: time },
          { slot: 'opt' }
        ],
        colConfigs1: [
          { prop: 'userName', label: '接受人', width: '250' },
          { prop: 'readFlag', label: '阅读状态', width: '250', formatter: readFlag },
          { prop: 'readDate', label: '阅读时间', width: '250', component: time },
          { slot: 'opt' }
        ],
        searchForm: {},
        searchFormList: {},
        searchFormList1: {},
        listLoading: true,
        listLoading1: true,
        dialogTitle: '新增通知',
        dialogTitle1: '通知详情',
        dialogType: 0,
        outerVisible1: false,
        teamRow: {
          roleType: []
        },
        teamRow1: {},
        teamRowClear: {},
        tableData: [],
        tableData1: [],
        notifyId: 0,
        pageNum: 1,
        pageNum1: 1,
        pageSize: 10,
        pageSize1: 10,
        total: 1,
        total1: 1,
        sum: 0,
        read: 0,
        notRead: 0,
        outerVisible: false,
        pca: pca,
        rules: {
          title: [
            { required: true, message: '请输入标题', trigger: 'change' }
          ],
          type: [
            { required: true, message: '请选择类型', trigger: 'change' }
          ],
          status: [
            { required: true, message: '请选择状态', trigger: 'change' }
          ],
          roleType: [
            { required: true, message: '请选择接受人类型', trigger: 'blur' }
          ]
        },
        visible: false,
        typeList: [
          { value: 1, label: '会议通告' },
          { value: 2, label: '业务处理' },
          { value: 3, label: '未到账' },
          { value: 4, label: '请求查看' },
          { value: 5, label: '证件过期类型' }
        ],
        readFlagList: [
          { value: 1, label: '已读' },
          { value: 2, label: '未读' }
        ]
      }
    },
    created() {
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      this.fetchData()
    },
    computed: {
      global() {
        return global
      },
      userId() {
        return this.$store.state.user.userId
      },
      roleType() {
        return this.$store.state.user.roleType
      },
      name() {
        return this.$store.state.user.name
      }
    },
    methods: {
      judge() {
        if (this.teamRow.roleType.indexOf(7) !== -1 && this.teamRow.roleType.indexOf(3) === -1) {
          this.teamRow.roleType.push(3)
        }
        if (this.teamRow.roleType.indexOf(8) !== -1 && this.teamRow.roleType.indexOf(4) === -1) {
          this.teamRow.roleType.push(4)
        }
        if (this.teamRow.roleType.indexOf(9) !== -1 && this.teamRow.roleType.indexOf(5) === -1) {
          this.teamRow.roleType.push(5)
        }
      },
      fetchData() {
        this.searchFormList.userId = this.userId
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.searchFormList.roleType = this.roleType
        this.listLoading = true
        getList(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          this.listLoading = false
        })
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      getUnreadCount() {
        getUnreadCount().then(response => {
          this.$store.dispatch('setUnread', response.responseBody)
        })
      },
      closeDialog() {
        this.fetchData()
        this.getUnreadCount()
      },
      addTeam() {
        this.outerVisible = true
        this.dialogTitle = '新增通知'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.dialogType = 1
        if (this.$refs.file) {
          this.$refs.file.value = ''
        }
      },
      lookTeam(scoperow) {
        this.outerVisible1 = true
        this.teamRow1 = {}
        this.tableData1 = []
        this.searchFormList1 = {
          roleType: this.roleType,
          userId: this.userId,
          type: scoperow.type,
          readFlag: scoperow.readFlag,
          notifyId: scoperow.notifyId
        }
        this.fetchData1()
        // this.$emit('changeNotifyId', scoperow.notifyId)
        // // this.$emit('changeNotifyId', scoperow.readFlag)
        // this.$emit('changeCard', 'informationadd')
      },
      fetchData1() {
        this.listLoading1 = true
        this.searchFormList1.pageNum = this.pageNum1
        this.searchFormList1.pageSize = this.pageSize1
        lookChart(this.searchFormList1).then(response => {
          this.teamRow1 = response.responseBody.notify
          this.teamRow1.type = parseInt(this.teamRow1.type)
          this.sum = response.responseBody.sum
          this.read = response.responseBody.read
          this.notRead = response.responseBody.notRead
          this.total1 = response.responseBody.notifyRecordPageInfo.total
          this.tableData1 = response.responseBody.notifyRecordPageInfo.list
          this.listLoading1 = false
        })
      },
      editTeam(notifyId) {
        this.outerVisible = true
        this.dialogTitle = '修改通知'
        this.dialogType = 0
        if (this.$refs.file) {
          this.$refs.file.value = ''
        }
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        const params = {
          notifyId: notifyId
        }
        selectSysteminfor(params).then(response => {
          this.teamRow = response.responseBody
          this.teamRow.roleType = this.teamRow.roleType.split(',')
          this.teamRow.type = parseInt(this.teamRow.type)
          for (let i = 0; i < this.teamRow.roleType.length; i++) {
            this.teamRow.roleType[i] = parseInt(this.teamRow.roleType[i])
          }
        })
      },
      notWarn(notifyId) {
        const params = {
          notifyId: notifyId,
          userId: this.userId
        }
        notWarn(params).then(response => {
          this.fetchData()
          getUnreadCount().then(response => {
            this.$store.dispatch('setUnread', response.responseBody)
          })
        })
      },
      submitForm(formName) {
        const params = new FormData()
        // // const createBy = this.$store.state.user.name
        // const userId = this.$store.state.user.userId
        if (!this.dialogType) {
          params.append('notifyId', this.teamRow.notifyId)
          params.append('updateBy', this.name)
        } else {
          params.append('createBy', this.name)
        }
        params.append('type', this.teamRow.type)
        params.append('userId', this.userId)
        params.append('title', this.teamRow.title)
        params.append('status', parseInt(this.teamRow.status))
        params.append('content', this.teamRow.content ? this.teamRow.content : '')
        if (this.teamRow.roleType.indexOf(11) !== -1) {
          params.append('roleType', '11')
        } else {
          params.append('roleType', this.teamRow.roleType.join(','))
        }
        if (this.teamRow.file) {
          params.append('file', this.teamRow.file)
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.dialogType) {
              addSysteminfor(params).then(response => {
                this.outerVisible = false
                this.fetchData()
                this.getUnreadCount()
              })
            } else {
              updateSysteminfor(params).then(response => {
                this.outerVisible = false
                this.fetchData()
                this.getUnreadCount()
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      deleteRow(scope) {
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = {
          notifyId: scope.row.notifyId,
          isDel: 1
        }
        deleteSysteminfor(params).then(response => {
          this.fetchData()
          this.getUnreadCount()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleSizeChange1(val) {
        this.pageSize1 = val
        this.fetchData1()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      handleCurrentChange1(val) {
        this.pageNum1 = val
        this.fetchData1()
      },
      getFile(event) {
        this.teamRow.file = event.target.files[0]
      },
      allowView(scope) {
        this.$refs[`popover-allowView${scope.$index}`].doClose()
        const params = {
          remarks: scope.row.remarks,
          notifyId: scope.row.notifyId,
          isAllow: 1
        }
        isAllow(params).then(response => {
          this.fetchData()
          this.getUnreadCount()
        })
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .nomal {
    display: inline-block;
    border-radius: 50%;
    width: 12px;
    height: 12px;
    margin-right: 5px;
  }

  .red {
    margin-left: 10px;
    background: #d81e06;
  }

  .green {
    background: #19fa28;
  }

  .span {
    margin-left: 24px;
  }

  .pagination {
    margin-left: 20px;
  }

  .dialog1 {
    display: inline;
    min-width: 500px;
  }

  .input1 {
    width: 140px;
  }

  .selectclass {
    width: 390px;
  }

  .app-container {
    height: auto;
    .el-pagination {
      margin-top: 20px;
    }
    .table-btn {
      margin-bottom: 10px;
      & > button {
        margin: 0 20px;
      }
      .el-dialog {
        textarea {
          margin-top: 10px;
        }
        .el-checkbox {
          margin-right: 20px;
        }
        .el-checkbox + .el-checkbox {
          margin-left: 0;
        }
      }
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .img {
    width: 20%;
  }

  .dialog1 {
    min-wid: 500px;
    /*max-wid: 800px;*/
    overflow: auto;
  }

  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  a, a:focus, a:hover {
    color: #409EFF;
  }

  /*.el-table__body tr.hover-row>td {
    background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
    background-color: #0000ff !important;
  }*/
</style>
